#include "serialdata.h"

#include <QDebug>
#include <QTimer>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QMessageBox>
#include "model/message.h"
SerialData::SerialData(GwInfo *info, QObject *parent) : QObject(parent)
{
    index=0;
    msg_queue=new QQueue<Message*>;
    msg_list=new QList<Message*>;
    port = nullptr;
    tik=new QTimer;
    tik->setInterval(200);
    connect(tik,&QTimer::timeout,this,&SerialData::time_out);
}

bool SerialData::reOpen(QString name,QSerialPort::BaudRate baud)
{
    if(port!= nullptr)
    {
        qDebug("already open");
        this->close();
    }
    port = new QSerialPort();
    port->setPortName(name);
    port->setBaudRate(baud);
    port->setDataBits(QSerialPort::Data8);
    if (!port->open(QIODevice::ReadWrite))
    {
        qDebug()<<"open "+name+" faild: "+port->errorString();
        delete port;
        port=nullptr;
        return false;
    }
    port->clear();
    connect(port,&QSerialPort::readyRead,this,&SerialData::readData);
    qDebug("port opened!");
    tik->start();
    return true;
}

void SerialData::writeData(QByteArray array)
{
    array.append(index);
    Message *msg=new Message(index,array);
    msg_queue->enqueue(msg);
    if(index==255)
    {
        index=0;
    }
    index++;
}
void SerialData::close()
{
    if (port != nullptr)
    {
        port->close();
        delete port;
        port = nullptr;
    }
}

void SerialData::time_out()
{
    if(!msg_queue->isEmpty())
    {
        Message *msg=msg_queue->dequeue();
        this->write_event(msg->get_msg());
        msg->start();
        qDebug()<<"添加指令！";
        this->msg_list->append(msg);
    }

    for (int i = msg_list->length()-1; i >=0; --i)
    {
        if(msg_list->at(i)->get_num()>=RESEND)
        {
            delete msg_list->takeAt(i);
        }
    }
    for(int i=msg_list->length()-1;i>=0;--i)
    {
        if(msg_list->at(i)->get_elapsed()>DELAY)
        {
            msg_queue->enqueue( msg_list->takeAt(i));
        }
    }
}
void SerialData::write_event(QByteArray array)
{
    if(this->port==nullptr|| !this->port->isOpen()||!this->port->isWritable())
    {
        qDebug()<<"串口不存在或打开失败！";
        return;
    }
    int len= this->port->write(array);
    QString str="";
    for(auto i:array)
    {
        str+=" "+QString("%1").arg((uchar)i,2,16,QLatin1Char('0')).toUpper();
    }
    qDebug()<<"发送："+str;
    qDebug()<<"长度："+QString::number(len);
}
void SerialData::readData()
{

    QByteArray array= this->port->readAll();
    if(array.length()<13)
    {
        qDebug()<<"lenght error";
    }
    int num=array.at(array.length()-1);
    for (int i = msg_list->length()-1; i >=0; --i)
    {
        qDebug()<<QString::number(msg_list->at(i)->get_num())+" "+QString::number(num);
        if(msg_list->at(i)->get_index()==num)
        {
            delete msg_list->takeAt(i);
            qDebug()<<"删除"+QString::number(i);
        }
    }

    QString s="";
    for(int i=0;i<array.length();++i)
    {
        s+=" "+QString::number((uchar)array.at(i),16);
    }
    qDebug()<<"source:"+s;
}
